<template>
  <w-overlay
    class="w-dialog"
    :model-value="showWrapper"
    :persistent="persistent"
    :persistent-no-animation="persistentNoAnimation"
    @click="onOutsideClick"
    :bg-color="overlayColor"
    :opacity="overlayOpacity"
    :class="classes"
  >
    <transition :name="transition" appear="appear" @after-leave="onClose">
      <w-card
        class="w-dialog__content"
        v-if="showContent"
        no-border="no-border"
        :title-class="titleClass"
        :content-class="contentClass"
        :title="title || undefined"
        :style="contentStyles"
      >
        <template v-if="$slots.title" v-slot:title>
          <slot name="title"></slot>
        </template>
        <slot></slot
        ><template v-if="$slots.actions" v-slot:actions>
          <slot name="actions"></slot>
        </template>
      </w-card>
    </transition>
  </w-overlay>
</template>
<script>
import { ref, computed, watch } from "vue";
export default {
  name: "w-dialog",

  props: {
    modelValue: { default: true },
    width: { type: [Number, String], default: 0 },
    fullscreen: { type: Boolean },
    persistent: { type: Boolean },
    persistentNoAnimation: { type: Boolean },
    tile: { type: Boolean },
    title: { type: String },
    transition: { type: String, default: "fade" }, // @todo: validator.
    titleClass: { type: String },
    contentClass: { type: String },
    overlayColor: { type: String },
    overlayOpacity: { type: [Number, String, Boolean] }
  },

  emits: ["input", "update:modelValue", "close"],
  setup(props, ctx) {
    const showWrapper = ref(props.modelValue);
    const showContent = ref(props.modelValue);

    const maxWidth = computed(() => {
      let width = props.width;
      if (width && parseInt(width) == width) width += "px";
      return width;
    });
    const classes = computed(() => {
      return {
        "w-dialog--fullscreen": props.fullscreen
      };
    });
    const contentStyles = computed(() => {
      return {
        maxWidth: !props.fullscreen && maxWidth.value ? maxWidth.value : null
      };
    });

    function onOutsideClick() {
      if (!props.persistent) {
        showContent.value = false;
        // If fade transition close both dialog and overlay at the same time
        // (don't need to wait for the end of the dialog transition).
        if (props.transition === "fade") {
          onClose();
        }
      }
    }
    function onClose() {
      showWrapper.value = false;
      ctx.emit("update:modelValue", false);
      ctx.emit("input", false);
      ctx.emit("close", false);
    }

    watch(
      () => props.modelValue,
      value => {
        if (value) {
          showWrapper.value = value;
        }
        showContent.value = value;
      }
    );

    return {
      showWrapper,
      showContent,
      maxWidth,
      classes,
      contentStyles,
      onOutsideClick,
      onClose
    };
  }
};
</script>
